package com.zxy.config.handler;

import cn.hutool.json.JSONObject;
import com.zxy.domain.WebUrl;
import com.zxy.mapper.WebUrlMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 路由拦截器 判断哪些路由打开了开关能够访问
 */
@Component
@Slf4j
public class WebUrlHandler implements HandlerInterceptor {

    @Resource
    private WebUrlMapper webUrlMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String uri = request.getRequestURI();
        if (!uri.equals("/favicon.ico") && !uri.equals("/error")){
            WebUrl webUrl = webUrlMapper.findEnableUrl(uri);
            if (webUrl==null){
                JSONObject object = new JSONObject();
                object.set("status","404");
                object.set("msg","Not Found Page");
                PrintWriter writer = response.getWriter();
                writer.println(object);
                writer.flush();
                writer.close();
                return false;
            }
            if (webUrl.isEnable()){
                return true;
            }else {
                JSONObject object = new JSONObject();
                object.set("msg","当前url未开启，请联系管理员");
                PrintWriter writer = response.getWriter();
                writer.println(object);
                writer.flush();
                writer.close();
                return false;
            }
        }
        return true;
    }
}
